package cn.virens.common.spring.filter;

import cn.virens.common.util.exception.APIException;
import org.springframework.util.PathMatcher;

public record PathPatternItem(PathPatternType type, PathMatcher matcher, String pattern) {
    /**
     * 生成白名单节点
     *
     * @param matcher
     * @param pattern
     * @return
     */
    public static PathPatternItem white(PathMatcher matcher, String pattern) {
        return new PathPatternItem(PathPatternType.white, matcher, pattern);
    }

    /**
     * 生成黑名单节点
     *
     * @param matcher
     * @param pattern
     * @return
     */
    public static PathPatternItem black(PathMatcher matcher, String pattern) {
        return new PathPatternItem(PathPatternType.black, matcher, pattern);
    }

    /**
     * 比较两个节点的顺序，大的在前面
     */
    public int compare(PathPatternItem other) throws APIException {
        return other.order() - order();
    }

    /**
     * 尝试对路径进行匹配
     *
     * @param path 路径
     * @return 返回对应规则类型
     */
    public boolean match(String path) throws APIException {
        return matcher.match(pattern, path);
    }

    /**
     * 是否是白名单
     */
    public boolean is_white() throws APIException {
        return type() == PathPatternType.white;
    }

    /**
     * 是否是黑名单
     */
    public boolean is_black() throws APIException {
        return type() == PathPatternType.black;
    }

    /**
     * 排序号，大的再前
     */
    public int order() throws APIException {
        return pattern.length();
    }
}
